home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++,rb.technical
- Subject: Re: Can copy constructor and operator= share code?
- Followup-To: comp.lang.c++,rb.technical
- Date: 4 Mar 1996 15:10:03 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Distribution: world
- Message-ID: <4hf14b$69q@dawn.mmm.com>
- References: <4h2kcn$40d@rap.SanDiegoCA.ATTGIS.COM> <4h525l$pja@rap.SanDiegoCA.ATTGIS.COM>
- Reply-To: kjhopps@mmm.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Jake Le (dle@costello.SanDiegoCA.ATTGIS.COM) wrote:
- > Boris,
-
- > You can call the operator= in your copy constructor.
-
- > Here is an example:
-
- > class CFoo {
-
- > public:
- > CFoo() { m_iSize = 0; };
- > CFoo(const CFoo &foo)
- > {
- > // Call the operator=
- > this->operator=(foo);
- > };
-
- > CFoo& operator=(const CFoo &foo)
- > {
- > m_iSize = foo.m_iSize;
- > return *this;
- > };
-
- > void Print() { cout << "Size = " << m_iSize << endl; };
- > void SetSize(int size) { m_iSize = size; };
-
- > int m_iSize; // Hungarian notation
- > };
-
- Be careful to initialize your members in the copy constructor before
- you call operator=(). If CFoo contained a pointer to dynamically
- allocated memory, this would not work well at all. Also, be sure
- in operator=() to handle the case where the object is being assigned
- to itself:
- if (&foo != this) {
- // do the work
- }
- --
- Kevin J. Hopps e-mail: kjhopps@mmm.com
- 3M Company phone: (612) 737-4643
- 3M Center, Bldg. 235-2D-57 fax: (612) 737-2700
- St. Paul, MN 55144-1000 Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-